package com.app.library.base

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.disposables.Disposable

open class LibViewModel : ViewModel() {

    private val composite: CompositeDisposable = CompositeDisposable()

    //异常处理
    protected val _exception = MutableLiveData<Throwable>()
    val exception: LiveData<Throwable> = _exception

    //Toast 内容
    protected val _toast = MutableLiveData<String>()
    val toast: LiveData<String> = _toast

    //加载框，null为隐藏，非空显示Loading
    protected val _loading = MutableLiveData<String?>()
    val loading: LiveData<String?> = _loading

    //加载框，null为隐藏，非空显示Loading
    protected val _refresh = MutableLiveData<Boolean>()
    val refresh: LiveData<Boolean> = _refresh

    protected fun addToLifecycle(disposable: Disposable) {
        this.composite.add(disposable)
    }

    /**
     * 通用加载提示
     * @param msg null的时候隐藏Loading
     */
    fun loading(msg: String? = null) {
        _loading.postValue(msg)
    }

    fun loadComplete() {
        _loading.postValue(null)
    }

    /**
     * 取消请求
     */
    fun dispose() {
        composite.dispose()
    }

    override fun onCleared() {
        dispose()
        super.onCleared()
    }

}